﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Media;

namespace KinectBender
{
    public class DeltaRenderingEventArgs : EventArgs
    {
        public TimeSpan Delta { get; private set; }
        public TimeSpan RenderingTime { get; private set; }

        public DeltaRenderingEventArgs(TimeSpan delta, TimeSpan renderingTime)
        {
            this.Delta = delta;
            this.RenderingTime = renderingTime;
        }
    }

    public static class CompositionTargetEx
    {
        private static TimeSpan _last = TimeSpan.Zero;
        private static event EventHandler<DeltaRenderingEventArgs> _FrameUpdating;
        public static event EventHandler<DeltaRenderingEventArgs> FrameUpdating
        {
            add
            {
                if (_FrameUpdating == null)
                    CompositionTarget.Rendering += CompositionTarget_Rendering;
                _FrameUpdating += value;
            }
            remove
            {
                _FrameUpdating -= value;
                if (_FrameUpdating == null)
                    CompositionTarget.Rendering -= CompositionTarget_Rendering;
            }
        }

        static void CompositionTarget_Rendering(object sender, EventArgs e)
        {
            RenderingEventArgs args = (RenderingEventArgs)e;
            if (args.RenderingTime == _last)
                return;
            DeltaRenderingEventArgs deltaArgs = new DeltaRenderingEventArgs(args.RenderingTime - _last, args.RenderingTime);
            _last = args.RenderingTime;
            _FrameUpdating(sender, deltaArgs);
        }
    }
}
